<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/17
 * Time: 下午5:44
 */

namespace App\Modules\Finance\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class FinancialStat 渠道提现信息（可提现，总提现...）
 * @package App\Modules\Finance\Models
 */
class FinancialStat extends Model
{
    protected $table = 'financial_stats';
    protected $fillable = ['distribution_channel_id', 'accumulative_withdrawal_amount', 'enable_withdrawal_amount', 'latest_withdrawal_amount', 'latest_withdraw_time', 'withdraw_pending_amount', 'commission_rate'];


    /**
     * 根据渠道ID获取FinancialStat
     * @param $distribution_channel_id
     * @return mixed
     */
    static function getByDistributionChannel($distribution_channel_id)
    {
        $result = self::where('distribution_channel_id', $distribution_channel_id)->first();
        return $result;
    }

    /**
     * 获取可提现金额总额
     * @param string $distribution_channel_id 不传获取所有渠道可提现金额总额
     * @return mixed
     */
    static function getEnableWithdrawalAmount($distribution_channel_id = '')
    {
        if ($distribution_channel_id) {
            return FinancialStat::where('distribution_channel_id', $distribution_channel_id)->sum('enable_withdrawal_amount');
        } else {
            return FinancialStat::sum('enable_withdrawal_amount');
        }
    }

    static function getFinancialStatInfo($params = [], $is_all = false)
    {
        $search_obj = self::join('distribution_channels', 'financial_stats.distribution_channel_id', '=', 'distribution_channels.id')
            ->join('channel_users', 'channel_users.id', '=', 'distribution_channels.channel_user_id');

        $search_obj->select('financial_stats.id', 'channel_users.id as channel_user_id', 'channel_users.phone', 'distribution_channels.id as distribution_channel_id', 'enable_withdrawal_amount','distribution_channels.nickname','distribution_channels.site_nick_name');

        if (isset($params['distribution_channel_ids']) && $params['distribution_channel_ids']) {
            $search_obj->whereIn('financial_stats.distribution_channel_id', $params['distribution_channel_ids']);
        }

        if (isset($params['distribution_channel_id']) && $params['distribution_channel_id']) {
            $search_obj->where('financial_stats.distribution_channel_id', $params['distribution_channel_id']);
        }

        $search_obj->where('enable_withdrawal_amount', '>', '0');

        if ($is_all) {
            return $search_obj->get();
        } else {
            return $search_obj->paginate();
        }
    }
}